package cn.fl.project.service.impl;

import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.*;
import cn.fl.capital.condition.CapPayInfoQueryCondition;
import cn.fl.capital.dto.CapPayInfoDTO;
import cn.fl.capital.service.ICapPayInfoApiService;
import cn.fl.changeapply.api.IPrjPrdChangeApplyApiService;
import cn.fl.changeapply.condition.PrjPrdChangeApplyQC;
import cn.fl.changeapply.constant.PrjPrdChangeApplyConstant;
import cn.fl.changeapply.dto.PrjPrdChangeApplyDTO;
import cn.fl.commons.result.ResponseData;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.preloan.IPrjPrdVehinfoApiService;
import cn.fl.preloan.condition.PrjPrdDtlGpsQueryCondition;
import cn.fl.preloan.condition.PrjPrdVehInfoQueryCondition;
import cn.fl.preloan.dto.PrjPrdVehInfoDTO;
import cn.fl.preloan.dto.PrjPrdVehInfoPageResponseDTO;
import cn.fl.prjprddtlgps.dto.PrjPrdDtlGpsDTO;
import cn.fl.prjprddtlgps.service.IPrjPrdDtlGpsService;
import cn.fl.prjprddtlgps.vo.PrjPrdDtlGpsVO;
import cn.fl.project.api.IPrjPrdGpsApplyApiService;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.constant.PrjPrdDtlConstant;
import cn.fl.project.constant.PrjPrdGpsApplyConstant;
import cn.fl.project.constant.PrjPrdVehInfoConstant;
import cn.fl.project.dto.PrjBscInfoDTO;
import cn.fl.project.dto.PrjPrdDtlDTO;
import cn.fl.project.dto.PrjPrdGpsApplyDTO;
import cn.fl.project.dto.PrjPrdPaySchMDTO;
import cn.fl.project.service.IPrjPrdPaySchMApiService;
import cn.fl.project.service.IPrjPrdVehInfoService;
import cn.fl.project.service.IProjectApiService;
import cn.fl.project.vo.PrjPrdDtlVO;
import cn.fl.project.vo.PrjPrdLicInfoVO;
import cn.fl.project.vo.PrjPrdVehInfoVO;
import cn.fl.system.transform.SysUlFilesRecVOTransform;
import cn.fl.system.vo.SysUlFilesRecVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import flow.business.facade.flow.api.IFlowBusinessQueryApiService;
import flow.business.facade.flow.condition.SysFlowSHQueryCondition;
import flow.business.facade.flow.dto.SysFlowSHDTO;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 实际车辆明细信息表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class PrjPrdVehInfoServiceImpl implements IPrjPrdVehInfoService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IPrjPrdVehInfoService.class);	
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IProjectApiService projectApiService;
	@Autowired
	private IUploadApiService uploadApiService;

	@Autowired
	private IPrjPrdDtlGpsService prjPrdDtlGpsService;

	@Autowired
	private IPrjPrdVehinfoApiService prjPrdVehinfoApiService;

	@Autowired
	private IPrjPrdGpsApplyApiService prjPrdGpsApplyApiService;

	@Autowired
	private IFlowBusinessQueryApiService flowBusinessQueryApiService;

	@Autowired
	private IPrjPrdPaySchMApiService prjPrdPaySchMApiService;

	@Autowired
	private IPrjPrdChangeApplyApiService prjPrdChangeApplyApiService;

	@Autowired
	private ICapPayInfoApiService capPayInfoApiService;

	@Override
	public PrjPrdVehInfoVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		//TODO 业务逻辑
		ResponseData<cn.fl.preloan.dto.PrjPrdVehInfoDTO> responseData = prjPrdVehinfoApiService.selectById(id,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
		PrjPrdVehInfoVO vo = new PrjPrdVehInfoVO();
		PrjPrdVehInfoDTO dto = responseData.getData();
		BeanUtils.copyProperties(dto,vo);
		if(null!= dto.getPrjPrdDtl()){
			PrjPrdDtlVO dtlVO = new PrjPrdDtlVO();
			BeanUtils.copyProperties(dto.getPrjPrdDtl(),dtlVO);
			vo.setPrjPrdDtl(dtlVO);
		}
		return vo;
//		PrjPrdVehInfoDTO dto = this.projectApiService.selectPrjPrdVehInfoById(id,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
//		return PrjPrdVehInfoVOTransform.toVO(dto);
	}

	@Override
	public Long add(PrjPrdVehInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		cn.fl.preloan.dto.PrjPrdVehInfoDTO dto = new cn.fl.preloan.dto.PrjPrdVehInfoDTO();
		BeanUtils.copyProperties(entity,dto);
		ResponseData<Long> responseData = prjPrdVehinfoApiService.add(dto);
		Long vehId = responseData.getData();
//		Long vehId = this.projectApiService.addPrjPrdVehInfo(PrjPrdVehInfoVOTransform.toDTO(entity));
		List<SysUlFilesRecVO> fileList = entity.getFileList();
		if(CollectionUtils.isNotEmpty(fileList)){
			 String orgCd = PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG;
						//查询项目的事业部
						PrjPrdDtlDTO dtl = this.projectApiService.selectPrjPrdDtlById(entity.getId());
						if(null!=dtl){
							PrjBscInfoDTO prjBsc = 	this.projectApiService.selectPrjBscInfoById(dtl.getPrjId(), CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
							if(null!=prjBsc){
								orgCd = prjBsc.getBuOrgCd();
							}
						}
			for (SysUlFilesRecVO sysUlFilesRecVO : fileList) {
				sysUlFilesRecVO.setPkId(String.valueOf(vehId));
				sysUlFilesRecVO.setTabNm("PRJ_PRD_VEH_INFO");
				sysUlFilesRecVO.setIsDel(BaseConstant.IS_YESNO_NO);
				sysUlFilesRecVO.setOrgCd(orgCd);
				sysUlFilesRecVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
				sysUlFilesRecVO.setCfgCd(PrjPrdVehInfoConstant.PRJ_PRD_VEH_FILE_CODE);
				sysUlFilesRecVO.setCfgDtlCd(PrjPrdVehInfoConstant.PRJ_PRD_VEH_FILE_DETAIL_CODE);
				this.uploadApiService.addSysUlFilesRec(SysUlFilesRecVOTransform.toDTO(sysUlFilesRecVO));
			}
		}
		return vehId;
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		//return this.prjPrdVehInfoApiService.removeById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
    		BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		};
		ResponseData responseData = prjPrdVehinfoApiService.removeByIds(ids);
		if(ResponseData.SUCCESS_CODE.equals(responseData.getCode())){
			return true;
		}else {
			return false;
		}
//		return projectApiService.removePrjPrdVehInfoByIds(ids);
    }

	@Override
	public boolean modify(PrjPrdVehInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
//		boolean flag = this.projectApiService.modifyPrjPrdVehInfo(PrjPrdVehInfoVOTransform.toDTO(entity));
		cn.fl.preloan.dto.PrjPrdVehInfoDTO dto = new cn.fl.preloan.dto.PrjPrdVehInfoDTO();
		BeanUtils.copyProperties(entity,dto);
		ResponseData responseData = prjPrdVehinfoApiService.modify(dto);
		boolean flag = false;
		if(ResponseData.SUCCESS_CODE.equals(responseData.getCode())){
			flag = true;
		}
		if(flag){
			List<SysUlFilesRecVO> fileList = entity.getFileList();
			if(CollectionUtils.isNotEmpty(fileList)){
				 
				 String orgCd = PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG;
							//查询项目的事业部
							PrjPrdDtlDTO dtl = this.projectApiService.selectPrjPrdDtlById(entity.getId());
							if(null!=dtl){
								PrjBscInfoDTO prjBsc = 	this.projectApiService.selectPrjBscInfoById(dtl.getPrjId(), CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
								if(null!=prjBsc){
									orgCd = prjBsc.getBuOrgCd();
								}
							}
			SysUlFilesRecQueryCondition ulQc = new SysUlFilesRecQueryCondition();
			ulQc.setPkId(String.valueOf(entity.getId()));
			this.uploadApiService.removeSysUlFilesRecByCondition(ulQc);
				for (SysUlFilesRecVO sysUlFilesRecVO : fileList) {
					sysUlFilesRecVO.setPkId(String.valueOf(entity.getId()));
					sysUlFilesRecVO.setTabNm("PRJ_PRD_VEH_INFO");
					sysUlFilesRecVO.setIsDel(BaseConstant.IS_YESNO_NO);
					sysUlFilesRecVO.setOrgCd(orgCd);
					sysUlFilesRecVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
					sysUlFilesRecVO.setCfgCd(PrjPrdVehInfoConstant.PRJ_PRD_VEH_FILE_CODE);
					sysUlFilesRecVO.setCfgDtlCd(PrjPrdVehInfoConstant.PRJ_PRD_VEH_FILE_DETAIL_CODE);
					this.uploadApiService.addSysUlFilesRec(SysUlFilesRecVOTransform.toDTO(sysUlFilesRecVO));
				}
			}
		}
		return flag;
	}

	@Override
	public boolean modifyPrjPrdVehAudStsCdByDtlId(Long prjPrdDtlId, String audStsCd) throws BaseException {
    	if(prjPrdDtlId==null || StringUtils.isBlank(audStsCd)){
			BaseLogUtils.info(logger, "modifyPrjPrdVehAudStsCdByDtlId", "修改合格证审核状态对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		ResponseData responseData = prjPrdVehinfoApiService.modifyVehAudStsCdByDtlId(prjPrdDtlId,audStsCd);
		if(ResponseData.SUCCESS_CODE.equals(responseData.getCode())){
			return true;
		}
		return false;
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		ResponseData<PrjPrdVehInfoPageResponseDTO> responseData = prjPrdVehinfoApiService.selectListPage(page.getEveryPage(),page.getCurrentPage(),
				(PrjPrdVehInfoQueryCondition)page.getCondition(),CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
		PrjPrdVehInfoPageResponseDTO pageDto = responseData.getData();
		List<PrjPrdVehInfoVO> list = new ArrayList<>();
		Pager pager = new Pager();
		if(null!=pageDto ){
			if( CollectionUtils.isNotEmpty(pageDto.getList())){
				for(PrjPrdVehInfoDTO dto : pageDto.getList()){
					PrjPrdVehInfoVO vo = new PrjPrdVehInfoVO();
					BeanUtils.copyProperties(dto,vo);
					// 添加GPS流程信息
					if(null != vo.getDtlId()){
						PrjPrdGpsApplyDTO gpsApplyDTO = prjPrdGpsApplyApiService.getLastByDtlId(vo.getDtlId());
						if(null!=gpsApplyDTO){
							SysFlowSHQueryCondition condition  = new SysFlowSHQueryCondition();
							condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
							condition.setDataId(gpsApplyDTO.getId());
							condition.setWordsInTheTable("PRJ");
							List<SysFlowSHDTO> sysFlowSHDTOList = flowBusinessQueryApiService.searchFlowSHList(condition);
							if(CollectionUtils.isNotEmpty(sysFlowSHDTOList)){
								SysFlowSHDTO sysFlowSHDTO = sysFlowSHDTOList.get(0);
								vo.setGpsPDefId(sysFlowSHDTO.getPDefId());
								vo.setGpsPDefKey(sysFlowSHDTO.getPDefKey());
								vo.setGpsPInsId(sysFlowSHDTO.getPInstId());
								vo.setGpsPNo(sysFlowSHDTO.getPNo());
								vo.setGpsPSts(String.valueOf(sysFlowSHDTO.getStatus()));
								vo.setGpsPBusId(String.valueOf(sysFlowSHDTO.getDataId()));
							}
						}
					}
					list.add(vo);
				}
			}
			pager.setTotalCount(pageDto.getTotalCount());
		}
//		Pager pager = 	this.projectApiService.searchPrjPrdVehInfoListPage(page,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
//		List<PrjPrdVehInfoVO> list =PrjPrdVehInfoVOTransform.toVOList((List<PrjPrdVehInfoDTO>)pager.getResultList());
		pager.setResultList(list);
		return pager;
	}
	@Override
	public List<PrjPrdVehInfoVO> searchList(PrjPrdVehInfoQueryCondition qc) throws BaseException{
		ResponseData<List<PrjPrdVehInfoDTO>> responseData = prjPrdVehinfoApiService.selectList(qc,CurrentThreadContext.getFlServiceSysCd(),CurrentThreadContext.getCurrentOrgCd());
		List<PrjPrdVehInfoVO> list = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(responseData.getData())){
			for(PrjPrdVehInfoDTO dto : responseData.getData()){
				PrjPrdVehInfoVO vo = new PrjPrdVehInfoVO();
				BeanUtils.copyProperties(dto,vo);
				list.add(vo);
			}
		}
		return list;
//		return PrjPrdVehInfoVOTransform.toVOList(this.projectApiService.searchPrjPrdVehInfoList(qc,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd()));
	}

	@Override
	public PrjPrdVehInfoVO selectByDtlId(Long dtlId) throws BaseException {
		ResponseData<PrjPrdVehInfoDTO>  responseData = prjPrdVehinfoApiService.selectByDtlId(dtlId,CurrentThreadContext.getFlServiceSysCd(),CurrentThreadContext.getCurrentOrgCd());
		PrjPrdVehInfoVO vo = new PrjPrdVehInfoVO();
		PrjPrdVehInfoDTO dto = responseData.getData();
		BeanUtils.copyProperties(dto,vo);
		if(null!= dto.getPrjPrdDtl()){
			PrjPrdDtlVO dtlVO = new PrjPrdDtlVO();
			BeanUtils.copyProperties(dto.getPrjPrdDtl(),dtlVO);
			vo.setPrjPrdDtl(dtlVO);
		}
		return vo;
//		return PrjPrdVehInfoVOTransform.toVO(this.projectApiService.selectByDtlId(dtlId,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd()));
	}

	@Override
	public Pager getPrjPrdDtlPrdInfoInitListPage(Pager page) throws BaseException {
		if(null==page) return new Pager();
		ResponseData<PrjPrdVehInfoPageResponseDTO> responseData = prjPrdVehinfoApiService.getPrjPrdDtlPrdInfoInitListPage(page.getEveryPage(),page.getCurrentPage(),
				(PrjPrdVehInfoQueryCondition)page.getCondition());
		PrjPrdVehInfoPageResponseDTO pageDto = responseData.getData();
		Pager pager = new Pager();
		if(null!=pageDto ){
			if( CollectionUtils.isNotEmpty(pageDto.getList())){
				List<PrjPrdVehInfoVO> list = new ArrayList<>();
				for(PrjPrdVehInfoDTO dto : pageDto.getList()){
					PrjPrdVehInfoVO vo = new PrjPrdVehInfoVO();
					BeanUtils.copyProperties(dto,vo);
					list.add(vo);
				}
				for (PrjPrdVehInfoVO prjPrdVehInfoVO : list) {
					prjPrdVehInfoVO.setGuidePc(DecimalUtils.convertFenToYuan(prjPrdVehInfoVO.getGuidePc().longValue()));
				}
				pager.setResultList(list);
			}
			pager.setTotalCount(pageDto.getTotalCount());
		}
//		Pager pager = this.projectApiService.getPrjPrdDtlPrdInfoInitListPage(page);
//		if(CollectionUtils.isNotEmpty(pager.getResultList())){
//			List<PrjPrdVehInfoVO> list = PrjPrdVehInfoVOTransform.toVOList((List<PrjPrdVehInfoDTO>)pager.getResultList());
//			for (PrjPrdVehInfoVO prjPrdVehInfoVO : list) {
//				prjPrdVehInfoVO.setGuidePc(DecimalUtils.convertFenToYuan(prjPrdVehInfoVO.getGuidePc().longValue()));
//			}
//			pager.setResultList(list);
//		}
		return pager;
	}

	@Override
	public PrjPrdVehInfoVO getPrjPrdVehInfoByScanStr(String baseStr) throws BaseException {
		PrjPrdVehInfoVO veh = new PrjPrdVehInfoVO();
		//解析合格证扫描结果
		
		 byte[] b = null;  
         String vehStr = null;  
         if (baseStr != null) {  
             BASE64Decoder decoder = new BASE64Decoder();  
             try {  
                 b = decoder.decodeBuffer(baseStr);  
                 if(null!=b){
                	 vehStr = new String(b, "gb2312");  
                	 if(vehStr.indexOf("|")<0){
                		 throw new BaseException("扫描失败！");
                	 }
                	 String[] vehStrArr = vehStr.split("\\|");
                	 String vin =vehStrArr[7];//根据vin查询数据
					 if(StringUtils.isBlank(vin)){ // 查询条件限制，防止数据爆表
						 throw new BaseException("扫描失败,VIN码为空！");
					 }
                	 PrjPrdVehInfoQueryCondition qc = new PrjPrdVehInfoQueryCondition();
                	 qc.setVin(vin);
                	 List<PrjPrdVehInfoVO> vehList = this.searchList(qc);
                	 if(CollectionUtils.isNotEmpty(vehList)){
                		 veh = vehList.get(0);
                	 }
                	 veh.setVehVersion(vehStrArr[0]);
                	 veh.setChsMdl(vehStrArr[1]);
                	 veh.setCertNo(vehStrArr[2]);
                	 veh.setMfrNm(vehStrArr[3]);
                	 veh.setVehNm(vehStrArr[4]);
                	 veh.setVehBr(vehStrArr[5]);
                	 veh.setPrdMdl(vehStrArr[6]);
                	 veh.setVin(vehStrArr[7]);
                	 veh.setEngNo(vehStrArr[9]);
                	 veh.setEngMdl(vehStrArr[10]);
                	 veh.setEmiStd(vehStrArr[11]);
                	 veh.setOutVol(vehStrArr[12]);
                	 veh.setMaxKw(vehStrArr[13]);
                	 veh.setRatedWgt(vehStrArr[14]);
                	 veh.setRatedSeatQty(vehStrArr[15]);
                	 if(StringUtils.isNotBlank(vehStrArr[16])){
                		 String dateStr = vehStrArr[16].substring(0,4)+"-"+vehStrArr[16].substring(5,7)+"-"+vehStrArr[16].substring(8,10);
                		 veh.setProDt(DateUtils.formatStringToDate(dateStr, DateUtils.YYYY_MM_DD));
                	 }
                	 veh.setCarCl(vehStrArr[17]);
                	 veh.setFuelTyp(vehStrArr[18]);
                	 veh.setTraTotWgt(vehStrArr[19]);
                	 veh.setCurbWgt(vehStrArr[20]);
                	 
                	 
                 }
             } catch (Exception e) {  
            	 BaseLogUtils.error(logger, "-", "异常", e);
            	 throw new BaseException("扫描失败！");
             }  
         }  
        return veh;
         
	}
	@Override
	public boolean checkPrjPrdVehVinExist(PrjPrdVehInfoQueryCondition qc) throws BaseException {
		String vin = qc.getVin();
		boolean flag = false;
		// TODO fixme
		ResponseData<List<PrjPrdVehInfoDTO>> responseData = prjPrdVehinfoApiService.getPrjPrdVehByVin(qc);
		List<PrjPrdVehInfoDTO> vehList = responseData.getData();
//		List<PrjPrdVehInfoDTO> vehList = this.projectApiService.getPrjPrdVehByVin(qc);
		if(CollectionUtils.isNotEmpty(vehList)){
			for (PrjPrdVehInfoDTO prjPrdVehInfoDTO : vehList) {
				String str = prjPrdVehInfoDTO.getVin().trim();
				if((!prjPrdVehInfoDTO.getPrdStsCd().equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_03))
			   &&(!prjPrdVehInfoDTO.getPrdStsCd().equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_05))
				&&(!prjPrdVehInfoDTO.getPrdStsCd().equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_12))
				&&(!prjPrdVehInfoDTO.getPrdStsCd().equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_14))
				&&(!prjPrdVehInfoDTO.getPrdStsCd().equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_16))
				&&(!prjPrdVehInfoDTO.getPrdStsCd().equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_22))
				&&(!prjPrdVehInfoDTO.getPrdStsCd().equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_40))
				&&str.equals(vin)){
					flag = true;
					break;
				}
			}
		}
		return flag;
	}


	@Override
	public DataResultDTO getGPSInfo(String gps) throws BaseException {
		//0表示失败 1表示成功
		// 峰云服务停止，考虑此方法调用点较多以及后期可能由其他服务代替，暂提供假实现
		DataResultDTO result = new DataResultDTO("0","峰云服务停止");
		/*DataResultDTO result = new DataResultDTO("1");
		String  url = PrjPrdGpsApplyConstant.GPS_URL+gps+"/";
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;

		JSONObject jsonObject = null;

		BaseLogUtils.info(logger, "getGPSInfo", "GPS位置第三方接口请求gps：" +gps);
		try {
			//请求发起客户端
			httpclient = HttpClients.createDefault();

			HttpPost post = new HttpPost(url);

			response = httpclient.execute(post);
			HttpEntity valueEntity = response.getEntity();
			String content = EntityUtils.toString(valueEntity);
			jsonObject = JSONObject.fromObject(content);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			result.setCode("0");
			result.setInfo(e.getMessage());
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			result.setCode("0");
			result.setInfo(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			result.setCode("0");
			result.setInfo(e.getMessage());
		}finally{
			if(httpclient != null){
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		result.setData(jsonObject);
		BaseLogUtils.info(logger, "getGPSInfo", "GPS位置第三方接口请求结束，返回：" + com.alibaba.fastjson.JSONObject.toJSONString(result));*/
		return result;
	}

	@Override
	public boolean submitChinaGPS(PrjPrdLicInfoVO prjPrdLicInfoVO) throws BaseException {

		BaseLogUtils.info(logger, "submitChinaGPS", "中交GPS入网请求prjPrdLicInfoVO：" + com.alibaba.fastjson.JSONObject.toJSONString(prjPrdLicInfoVO));

		//请求URL POST方式
		String url = PropertiesUtils.getProperty(PrjPrdGpsApplyConstant.SUBMIT_CHINA_GPS_URL);
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		boolean flag = false;
		try {
			//请求发起客户端
			httpclient = HttpClients.createDefault();
			HttpPost post = new HttpPost(url);

			//查询GPS设备号
			List<PrjPrdDtlGpsVO> gpsList = new ArrayList<>();
			PrjPrdDtlGpsQueryCondition qc = new PrjPrdDtlGpsQueryCondition();
			if (prjPrdLicInfoVO.getId() != null) {
				qc.setPrjDtlId(prjPrdLicInfoVO.getId());
				gpsList = prjPrdDtlGpsService.searchList(qc);
			}
			BaseLogUtils.info(logger, "submitChinaGPS", "查询GPS设备号参数:" + com.alibaba.fastjson.JSONObject.toJSONString(qc));
			BaseLogUtils.info(logger, "submitChinaGPS", "查询GPS设备号gpsList:" + com.alibaba.fastjson.JSONObject.toJSONString(gpsList));

			if (prjPrdLicInfoVO.getId() != null && (prjPrdLicInfoVO.getPrjId() == null || StringUtils.isEmpty(prjPrdLicInfoVO.getPaySchNo()))) {
				//查询车辆变更表，换车信息初期没有绑定项目及支付表
				PrjPrdChangeApplyQC prjPrdChangeApplyQC = new PrjPrdChangeApplyQC();
				prjPrdChangeApplyQC.setNewPrjPrdDtlId(prjPrdLicInfoVO.getId());
				prjPrdChangeApplyQC.setChangeTypeCd(PrjPrdChangeApplyConstant.CHANGE_TYPE_CD_2);
				prjPrdChangeApplyQC.setIsDel(0);
				BaseLogUtils.newLogger("中交GPS入网查询变更信息Start.dtlId:{},qc:{}", prjPrdLicInfoVO.getId(), JSON.toJSONString(prjPrdChangeApplyQC)).info();
				List<PrjPrdChangeApplyDTO> dtoList = this.prjPrdChangeApplyApiService.selectList(prjPrdChangeApplyQC, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
				BaseLogUtils.newLogger("中交GPS入网查询变更信息End.dtlId:{},dtoList:{}", prjPrdLicInfoVO.getId(), JSON.toJSONString(dtoList)).info();
				if (CollectionUtils.isNotEmpty(dtoList)) {
					PrjPrdChangeApplyDTO prjPrdChangeApplyDTO = dtoList.get(0);
					if (prjPrdLicInfoVO.getPrjId() == null) {
						prjPrdLicInfoVO.setPrjId(prjPrdChangeApplyDTO.getPrjId());
					}
					if (prjPrdLicInfoVO.getCstId() == null) {
						prjPrdLicInfoVO.setCstId(prjPrdChangeApplyDTO.getCstId());
					}
					if (StringUtils.isEmpty(prjPrdLicInfoVO.getCstNm())) {
						prjPrdLicInfoVO.setCstNm(prjPrdChangeApplyDTO.getCstNm());
					}
					if (prjPrdLicInfoVO.getCstMgrId() == null) {
						prjPrdLicInfoVO.setCstMgrId(prjPrdChangeApplyDTO.getCstMgrId());
					}
					if (StringUtils.isEmpty(prjPrdLicInfoVO.getCstMgrNm())) {
						prjPrdLicInfoVO.setCstMgrNm(prjPrdChangeApplyDTO.getCstMgrNm());
					}
					if (StringUtils.isEmpty(prjPrdLicInfoVO.getCstMgrOrgCD())) {
						prjPrdLicInfoVO.setCstMgrOrgCD(prjPrdChangeApplyDTO.getCstMgrOrgCd());
					}
					//用旧的dtlId查询支付表ID和支付表号
					if (prjPrdChangeApplyDTO.getPrjPrdDtlId() != null) {
						CapPayInfoQueryCondition condition = new CapPayInfoQueryCondition();
						condition.setPrjPrdDtlId(prjPrdChangeApplyDTO.getPrjPrdDtlId());
						condition.setIsDel(0);
						BaseLogUtils.newLogger("中交GPS入网查询付款信息Start.prjId:{},qc:{}", prjPrdLicInfoVO.getPrjId(), JSON.toJSONString(condition)).info();
						List<CapPayInfoDTO> capPayInfoDTOS = this.capPayInfoApiService.searchCapPayInfoList(condition);
						if (CollectionUtils.isNotEmpty(capPayInfoDTOS)) {
							CapPayInfoDTO capPayInfoDTO = capPayInfoDTOS.get(0);
							if (StringUtils.isEmpty(prjPrdLicInfoVO.getPaySchNo())) {
								prjPrdLicInfoVO.setPaySchNo(capPayInfoDTO.getPaySchNo());
							}
							if (prjPrdLicInfoVO.getPaySchId() == null) {
								prjPrdLicInfoVO.setPaySchId(capPayInfoDTO.getPaySchId());
							}
						}
					}
				}
			}
			//设置请求体
			com.alibaba.fastjson.JSONObject params = new com.alibaba.fastjson.JSONObject();
			params.put("prjId", prjPrdLicInfoVO.getPrjId());
			params.put("usrId", prjPrdLicInfoVO.getCstId());
			params.put("usrNm", prjPrdLicInfoVO.getCstNm());
			params.put("cstMgrId", prjPrdLicInfoVO.getCstMgrId());
			params.put("cstMgrNm", prjPrdLicInfoVO.getCstMgrNm());
			params.put("cstMgrOrgCd", prjPrdLicInfoVO.getCstMgrOrgCD());

			//组装GPS设备号参数
			List<Object> gpsRequestList = new ArrayList<>();
			for (int i = 0; i < gpsList.size(); i++) {
				if (!"0".equals(gpsList.get(i).getGpsCardNo())) {
					Map<String, Object> gpsRequestMap = new HashMap<>();
					gpsRequestMap.put("gpsDeviceType", "");
					gpsRequestMap.put("gpsDeviceNo", gpsList.get(i).getGpsCardNo());
					gpsRequestList.add(gpsRequestMap);
				}
			}

			Map<String,Object> map = new HashMap<>();
			map.put("carNo",prjPrdLicInfoVO.getVehNo());
			map.put("vin",prjPrdLicInfoVO.getVin());
			map.put("paySchNo", prjPrdLicInfoVO.getPaySchNo());
			//查询起租日
			if (StringUtils.isNotEmpty(prjPrdLicInfoVO.getPaySchId())) {
				BaseLogUtils.info(logger, "submitChinaGPS", "查询起租日Start paySchId:" + prjPrdLicInfoVO.getPaySchId());
				PrjPrdPaySchMDTO prjPrdPaySchMDTO = this.prjPrdPaySchMApiService.selectPrjPrdPaySchMById(prjPrdLicInfoVO.getPaySchId());
				BaseLogUtils.info(logger, "submitChinaGPS", "查询起租日End paySchId:" + prjPrdLicInfoVO.getPaySchId() + ",resp:" + com.alibaba.fastjson.JSONObject.toJSONString(prjPrdPaySchMDTO));
				if (prjPrdPaySchMDTO != null && prjPrdPaySchMDTO.getLsDt() != null) {
					map.put("lsDt", prjPrdPaySchMDTO.getLsDt().getTime());
				}
			}
			map.put("sivGpsDevice",JSONArray.parseArray(JSON.toJSONString(gpsRequestList)));
			List<Object> list = new ArrayList<>();
			list.add(map);
			params.put("vechileInfo", JSONArray.parseArray(JSON.toJSONString(list)));

			BaseLogUtils.info(logger, "submitChinaGPS", "中交GPS入网请求url：" + url);
			BaseLogUtils.info(logger, "submitChinaGPS", "中交GPS入网请求参数：" + params.toJSONString());

			post.setHeader("Content-Type", "application/json");
			post.setEntity(new StringEntity(params.toJSONString(), "UTF-8"));

			response = httpclient.execute(post);
			HttpEntity valueEntity = response.getEntity();
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String content = EntityUtils.toString(valueEntity);
				BaseLogUtils.info(logger, "submitChinaGPS", "中交GPS入网返回结果：" + content);
			}
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			BaseLogUtils.info(logger, "submitChinaGPS", "中交GPS入网失败：" + e.getMessage());
			throw new BaseException("中交GPS入网失败！");
		} finally {
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return flag;
		}
	}

	@Override
	public PrjPrdDtlGpsDTO getChinaGPSInfo(String vehNo) throws BaseException {
		//请求URL POST方式
		String url = PropertiesUtils.getProperty(PrjPrdGpsApplyConstant.CHINA_GPS_URL);
		BaseLogUtils.info(logger, "getChinaGPSInfo", "获取最新中交GPS信息请求URL：" + url);

		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		PrjPrdDtlGpsDTO gpsDTO = new PrjPrdDtlGpsDTO();

		try {
			//请求发起客户端
			httpclient = HttpClients.createDefault();
			HttpPost post = new HttpPost(url);
			//设置请求体
			String body = "{\"carNo\": \"" + vehNo + "\"}";
			BaseLogUtils.info(logger, "getChinaGPSInfo", "获取最新中交GPS信息请求参数：" + body);

			post.addHeader(HTTP.CONTENT_TYPE, "application/json");
			StringEntity se = new StringEntity(body, "UTF-8");
			se.setContentType("application/json");
			post.setEntity(se);
			response = httpclient.execute(post);
			BaseLogUtils.info(logger, "getChinaGPSInfo", "获取最新中交GPS信息返回结果response：" + response);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String content = EntityUtils.toString(response.getEntity());
				BaseLogUtils.info(logger, "getChinaGPSInfo", "获取最新中交GPS信息返回结果：" + content);
				if (StringUtils.isNotBlank(content)) {
					com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(content);
					//组装GPS信息
					gpsDTO.setOnlineType(jsonObject.getString("onOffLine"));//GPS在线状态
					String lon = jsonObject.getString("lon");
					String lat = jsonObject.getString("lat");

					if (StringUtils.isNotEmpty(lon) && StringUtils.isNotEmpty(lat)) {
						//经度
						gpsDTO.setLng(lon);
						//维度
						gpsDTO.setLat(lat);
						//对接百度地图API根据经纬度获取地址
						gpsDTO.setGpsAddrInfo(getAddressByBaiduMap(lat, lon));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			BaseLogUtils.info(logger, "getChinaGPSInfo", "获取最新中交GPS信息失败：" + e.getMessage());
			throw new BaseException("获取中交GPS失败！");
		} finally {
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return gpsDTO;
	}

	@Override
	public String getAddressByBaiduMap(String lat, String lng) throws BaseException {
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		String address = "";

		String url = PrjPrdGpsApplyConstant.BAIDU_MAP_URL + "?ak=" + PrjPrdGpsApplyConstant.BAIDU_MAP_AK + "&output=json&coordtype=wgs84ll&location=" + lat + "," + lng;
		BaseLogUtils.info(logger, "getAddressByBaidu", "百度地图获取地址请求参数：" + url);
		try {
			httpclient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(url);
			response = httpclient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String result = EntityUtils.toString(response.getEntity());
				if (StringUtils.isNotBlank(result)) {
					com.alibaba.fastjson.JSONObject resultJson = com.alibaba.fastjson.JSONObject.parseObject(result);
					String addressResult = resultJson.getString("result");
					if (StringUtils.isNotBlank(addressResult)) {
						address = com.alibaba.fastjson.JSONObject.parseObject(addressResult).getString("formatted_address");
					}
				}
				BaseLogUtils.info(logger, "getAddressByBaidu", "百度地图获取地址返回结果：" + result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("百度地图获取地址失败！");
		} finally {
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return address;
	}

}
